{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Two Brains in My Laptop\n",
    "## Center Processing Units (CPU)\n",
    "![](cpu.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "processor\t: 0\r\n",
      "vendor_id\t: GenuineIntel\r\n",
      "cpu family\t: 6\r\n",
      "model\t\t: 142\r\n",
      "model name\t: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz\r\n",
      "stepping\t: 9\r\n",
      "microcode\t: 0x62\r\n",
      "cpu MHz\t\t: 2700.000\r\n",
      "cache size\t: 3072 KB\r\n",
      "physical id\t: 0\r\n",
      "siblings\t: 4\r\n",
      "core id\t\t: 0\r\n",
      "cpu cores\t: 2\r\n",
      "apicid\t\t: 0\r\n",
      "initial apicid\t: 0\r\n",
      "fpu\t\t: yes\r\n",
      "fpu_exception\t: yes\r\n",
      "cpuid level\t: 22\r\n",
      "wp\t\t: yes\r\n",
      "flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp\r\n",
      "bugs\t\t: cpu_meltdown spectre_v1 spectre_v2\r\n",
      "bogomips\t: 5424.00\r\n",
      "clflush size\t: 64\r\n",
      "cache_alignment\t: 64\r\n",
      "address sizes\t: 39 bits physical, 48 bits virtual\r\n",
      "power management:\r\n",
      "\r\n",
      "processor\t: 1\r\n",
      "vendor_id\t: GenuineIntel\r\n",
      "cpu family\t: 6\r\n",
      "model\t\t: 142\r\n",
      "model name\t: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz\r\n",
      "stepping\t: 9\r\n",
      "microcode\t: 0x62\r\n",
      "cpu MHz\t\t: 2700.000\r\n",
      "cache size\t: 3072 KB\r\n",
      "physical id\t: 0\r\n",
      "siblings\t: 4\r\n",
      "core id\t\t: 1\r\n",
      "cpu cores\t: 2\r\n",
      "apicid\t\t: 2\r\n",
      "initial apicid\t: 2\r\n",
      "fpu\t\t: yes\r\n",
      "fpu_exception\t: yes\r\n",
      "cpuid level\t: 22\r\n",
      "wp\t\t: yes\r\n",
      "flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp\r\n",
      "bugs\t\t: cpu_meltdown spectre_v1 spectre_v2\r\n",
      "bogomips\t: 5424.00\r\n",
      "clflush size\t: 64\r\n",
      "cache_alignment\t: 64\r\n",
      "address sizes\t: 39 bits physical, 48 bits virtual\r\n",
      "power management:\r\n",
      "\r\n",
      "processor\t: 2\r\n",
      "vendor_id\t: GenuineIntel\r\n",
      "cpu family\t: 6\r\n",
      "model\t\t: 142\r\n",
      "model name\t: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz\r\n",
      "stepping\t: 9\r\n",
      "microcode\t: 0x62\r\n",
      "cpu MHz\t\t: 2700.000\r\n",
      "cache size\t: 3072 KB\r\n",
      "physical id\t: 0\r\n",
      "siblings\t: 4\r\n",
      "core id\t\t: 0\r\n",
      "cpu cores\t: 2\r\n",
      "apicid\t\t: 1\r\n",
      "initial apicid\t: 1\r\n",
      "fpu\t\t: yes\r\n",
      "fpu_exception\t: yes\r\n",
      "cpuid level\t: 22\r\n",
      "wp\t\t: yes\r\n",
      "flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp\r\n",
      "bugs\t\t: cpu_meltdown spectre_v1 spectre_v2\r\n",
      "bogomips\t: 5424.00\r\n",
      "clflush size\t: 64\r\n",
      "cache_alignment\t: 64\r\n",
      "address sizes\t: 39 bits physical, 48 bits virtual\r\n",
      "power management:\r\n",
      "\r\n",
      "processor\t: 3\r\n",
      "vendor_id\t: GenuineIntel\r\n",
      "cpu family\t: 6\r\n",
      "model\t\t: 142\r\n",
      "model name\t: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz\r\n",
      "stepping\t: 9\r\n",
      "microcode\t: 0x62\r\n",
      "cpu MHz\t\t: 2700.000\r\n",
      "cache size\t: 3072 KB\r\n",
      "physical id\t: 0\r\n",
      "siblings\t: 4\r\n",
      "core id\t\t: 1\r\n",
      "cpu cores\t: 2\r\n",
      "apicid\t\t: 3\r\n",
      "initial apicid\t: 3\r\n",
      "fpu\t\t: yes\r\n",
      "fpu_exception\t: yes\r\n",
      "cpuid level\t: 22\r\n",
      "wp\t\t: yes\r\n",
      "flags\t\t: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp\r\n",
      "bugs\t\t: cpu_meltdown spectre_v1 spectre_v2\r\n",
      "bogomips\t: 5424.00\r\n",
      "clflush size\t: 64\r\n",
      "cache_alignment\t: 64\r\n",
      "address sizes\t: 39 bits physical, 48 bits virtual\r\n",
      "power management:\r\n",
      "\r\n"
     ]
    }
   ],
   "source": [
    "# for linux, to see CPU info\n",
    "!cat /proc/cpuinfo\n",
    "# for OSX, it is\n",
    "# !sysctl -a|grep machdep.cpu "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### FLoating Point Operations Per Second (FLOPS)\n",
    "`CPU FLOPS = Number of Cores ∗ Average frequency ∗ Operations per cycle`\n",
    "\n",
    "#### single-precision floating point operations\n",
    "$+, -, *, /, \\ldots$ operations of single-precision (32 bit) floating point numbers.\n",
    "\n",
    "#### operations per cycle\n",
    "Instruction Set Extensions of `Core i5-7200U`: Intel® SSE4.1, Intel® SSE4.2, Intel® AVX2\n",
    "\n",
    "For Advanced Vector Extensions 2 (AVX2), width of the **Single Instruction Multiple Data** (SIMD) register file is 256\n",
    "\n",
    "![](simd.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Theoretical computation power of my CPU = 40.0 GFLOPS\n"
     ]
    }
   ],
   "source": [
    "operations_per_cycle = 256 / 32  # single precision (4 byte)\n",
    "GFLOPS_CPU = 2 * 2.5 * operations_per_cycle\n",
    "print('Theoretical computation power of my CPU = %s GFLOPS'%GFLOPS_CPU)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Graphics Processing Units (GPU)\n",
    "![](gpu.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GPU at BusId 0x3c doesn't have a supported video decoder\n",
      "** Message: PRIME: Requires offloading\n",
      "** Message: PRIME: is it supported? yes\n"
     ]
    }
   ],
   "source": [
    "!nvidia-settings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`GPU FLOPS = Number of CUDA cores * 2 * Average frequency`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Theoretical computation power of my GPU = 913.152 GFLOPS\n"
     ]
    }
   ],
   "source": [
    "GFLOPS_CPU = 384 * 2 * 1.189\n",
    "print('Theoretical computation power of my GPU = %s GFLOPS'%GFLOPS_CPU)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A simple benchmark\n",
    "Matrix multiplication test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100 loops, best of 3: 18 ms per loop\n"
     ]
    },
    {
     "ename": "RuntimeError",
     "evalue": "cuda runtime error (46) : all CUDA-capable devices are busy or unavailable at /pytorch/torch/lib/THC/generic/THCStorage.cu:58",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-4-229597a2da94>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[0;31m# upload data to GPU, do the same calculation\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0mAC\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mA\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcuda\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     10\u001b[0m \u001b[0mBC\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mB\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcuda\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     11\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmagic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'timeit -n 100 CC = AC.mm(BC)'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/leo/anaconda3/lib/python3.6/site-packages/torch/_utils.py\u001b[0m in \u001b[0;36m_cuda\u001b[0;34m(self, device, async)\u001b[0m\n\u001b[1;32m     67\u001b[0m         \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     68\u001b[0m             \u001b[0mnew_type\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mgetattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcuda\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__class__\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__name__\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 69\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mnew_type\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msize\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcopy_\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0masync\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     70\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     71\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/leo/anaconda3/lib/python3.6/site-packages/torch/cuda/__init__.py\u001b[0m in \u001b[0;36m_lazy_new\u001b[0;34m(cls, *args, **kwargs)\u001b[0m\n\u001b[1;32m    359\u001b[0m     \u001b[0;31m# We need this method only for lazy init, so we can remove it\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    360\u001b[0m     \u001b[0;32mdel\u001b[0m \u001b[0m_CudaBase\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__new__\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 361\u001b[0;31m     \u001b[0;32mreturn\u001b[0m \u001b[0msuper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_CudaBase\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcls\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m__new__\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcls\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    362\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    363\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mRuntimeError\u001b[0m: cuda runtime error (46) : all CUDA-capable devices are busy or unavailable at /pytorch/torch/lib/THC/generic/THCStorage.cu:58"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "N = 1024\n",
    "A = torch.randn(N, N)\n",
    "B = torch.randn(N, N)\n",
    "%timeit -n 100 C = A.mm(B)\n",
    "\n",
    "# upload data to GPU, do the same calculation\n",
    "AC = A.cuda()\n",
    "BC = B.cuda()\n",
    "%timeit -n 100 CC = AC.mm(BC)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wed Feb 14 21:52:24 2018       \r\n",
      "+-----------------------------------------------------------------------------+\r\n",
      "| NVIDIA-SMI 390.25                 Driver Version: 390.25                    |\r\n",
      "|-------------------------------+----------------------+----------------------+\r\n",
      "| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\r\n",
      "| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\r\n",
      "|===============================+======================+======================|\r\n",
      "|   0  GeForce 940MX       Off  | 00000000:3C:00.0 Off |                  N/A |\r\n",
      "| N/A   83C    P0    N/A /  N/A |    972MiB /  2004MiB |    100%      Default |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "                                                                               \r\n",
      "+-----------------------------------------------------------------------------+\r\n",
      "| Processes:                                                       GPU Memory |\r\n",
      "|  GPU       PID   Type   Process name                             Usage      |\r\n",
      "|=============================================================================|\r\n",
      "|    0      1101      G   /usr/lib/xorg/Xorg                           211MiB |\r\n",
      "|    0      1806      G   compiz                                       134MiB |\r\n",
      "|    0      5163      C   /home/leo/anaconda3/bin/python               195MiB |\r\n",
      "|    0      5355      G   ...-token=03B0BC2B348F3C5EFDFAD6298DA935B9   204MiB |\r\n",
      "|    0      7240      C   /home/leo/anaconda3/bin/python               202MiB |\r\n",
      "+-----------------------------------------------------------------------------+\r\n"
     ]
    }
   ],
   "source": [
    "# run only if you have an Nvidia graphic card, with driver properly configured\n",
    "!nvidia-smi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Remarks\n",
    "* A GPU have its own memory, while a CPU uses system memomry,\n",
    "* FLOPS of GPU is much larger than CPU,\n",
    "* Single thread performance of CPU is much better than GPU."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
